package SecondeStage.FanShe;

import java.lang.reflect.Constructor;
@SuppressWarnings({"all"})
public class ReflectCreateInstance {
    public static void main(String[] args) throws Exception {
        // 演示通过反射机制创建实例
        //1. 先获取到User类的Class对象
        Class<?> userClass = Class.forName("SecondeStage.FanShe.User");
        //2. 通过public的无参构造器创建实例
        userClass.newInstance();
        //3. 通过public的有参构造器创建实例
        /*
        / 此时constructor 对象就是
               public User(String name) {
                    this.name = name;
                }
         */
        Constructor<?> constructor = userClass.getConstructor(String.class);
        Object user1 = constructor.newInstance("hsp");
        System.out.println("user1="+user1);
        //4. 通过非public的有参构造器创建实例
        //(1)得到private的构造器对象
        Constructor<?> constructor1=userClass.getDeclaredConstructor(String.class,int.class);
        //(2) 创建实例
        constructor1.setAccessible(true); //暴破: 使用反射可以访问private构造器
        Object user2 = constructor1.newInstance("张三丰",100);
        System.out.println("user2="+user2);
    }
}

class User{
    private int age;
    private String name;

    // 公有无参构造器
    public User() {
    }

    // 公有有参构造器
    public User(String name) {
        this.name = name;
    }
    // 私有有参构造器
    private User(String name,int age) {
        this.name =name;
        this.age = age;
    }

    public int getAge() {
        return age;
    }

    public void setAge(int age) {
        this.age = age;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    @Override
    public String toString() {
        return "User{" +
                "age=" + age +
                ", name='" + name + '\'' +
                '}';
    }
}